<?php

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;

class IndexController extends BaseController
{

    public function setRedPacket(Request $request)
    {
        $body = $request->post();

        if (!isset($body['total']) && empty($body['total'])) {
            abort(500, '输入红包金额');
        }

        if (!isset($body['num']) && empty($body['num'])) {
            abort(500, '输入红包个数');
        }

        $total = $body['total'];

        $num = (int) $body['num'];

        $use = 0;
        $list = [];
        for ($i = 0; $i < $num; $i++) {
            if ($i === $num - 1) {
                $list[$i] = $total - $use;
            } else {
                $avg = ($total - $use) * 2 / ($num - $i);
                $list[$i] = 1 + mt_rand(0, $avg - 1);
            }
            $use = $use + $list[$i];
        }

        $n = redis()->incr("red_packet_key");

        $key = 'red_packet_key' . $n;

        redis()->lPush($key, $list);//将红包放入队列

        redis()->expire($key, 3600 * 24 * 3);//设置红包3天过期

        return $this->success(['data' => $list, 'total' => array_sum($list)]);
    }

    public function robRedPacket(Request $request)
    {
        $redId = (int) $request->query('red_packet_id');
        $userId = (string) $request->query('user_id');

        $consumeKey = 'red_packet_consume_key' . $redId;

        $packet = redis()->hGet($consumeKey, $userId);

        if (is_null($packet)) {
            $one = redis()->lPop('red_packet_key' . $redId);

            if (!is_null($one)) {
                redis()->hSet($consumeKey, $userId, $one);

                // todo 异步把数据持久化到MYSQL
                return $this->success('你抢到了' . $one . '元');
            }

            return $this->throwBusinessException([500, '红包已抢完'], '红包已抢完');
        }

        return $this->throwBusinessException([500, '红包已抢过'], '红包已抢过');
    }
}
